package heven.holt.wan.android.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import heven.holt.wan.android.extensions.requestCoroutine
import heven.holt.wan.android.model.UserModel
import heven.holt.wan.android.repository.WanUserRepository
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class UserViewModel @Inject constructor(
    private val wanUserRepository: WanUserRepository
) : ViewModel() {
    val userInfoLiveData: MutableLiveData<UserModel> =
        MutableLiveData(wanUserRepository.getUserInfo())

    val loginState: MutableLiveData<Boolean> = MutableLiveData()

    fun login(username: String, password: String) {
        viewModelScope.launch {
            val userModel =
                requestCoroutine { wanUserRepository.login(username, password) } ?: return@launch
            wanUserRepository.saveUserInfo(userModel)
            userInfoLiveData.postValue(userModel)
            loginState.postValue(true)
        }
    }

    fun isLogin(): Boolean = wanUserRepository.isLogin()
}